package net.sourceforge.j2meautonetwork.operation;

import java.io.DataInputStream;
import java.io.DataOutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import net.sourceforge.j2meautonetwork.model.User;
import net.sourceforge.j2meautonetwork.util.CodeDefine;
import net.sourceforge.j2meautonetwork.util.Utilities;

/**
 * 网络探测器.
 * @author Steven King(woyaoying@hotmail.com)
 * @version 0.3
 */
public final class NetworkDetector implements Runnable {

    private boolean connected;
    
    private DataInputStream httpdis = null;
    private DataOutputStream httpdos = null;
    private HttpConnection httpconn = null;
    
    private boolean runningOver = false;
    
  
    /**
     * 尝试连接网络.
     * @param originalUrl
     * @throws Throwable
     */
    private void tryConnect(String originalUrl, boolean isProxy) throws Throwable {
        String hostName, servlet, url;
        if (originalUrl.toLowerCase().indexOf("http://") < 0) {
            originalUrl = "http://" + originalUrl;
        }
        int pos1 = "http://".length();
        int pos2 = originalUrl.indexOf('/', pos1);
        if (pos2 < 0) {
            hostName = originalUrl.substring(pos1);
            servlet = "";
        } else {
            hostName = originalUrl.substring(pos1, pos2);
            servlet = originalUrl.substring(pos2);
        }

        int pos3 = hostName.indexOf(":");

        if (pos3 < 0) {
            hostName += ":80";
        }

        if (isProxy) {
            url = "http://10.0.0.172:80" + servlet;
        } else {
            url = "http://" + hostName + servlet;
        }
        httpconn = (HttpConnection) Connector.open(url);
        if (isProxy) {
            httpconn.setRequestProperty(CodeDefine.HTTP_PROXY_HOST_HEADER,
                    hostName);
            httpconn.setRequestProperty(CodeDefine.HTTP_ACCEPT[0],
                    CodeDefine.HTTP_ACCEPT[1]);
            httpconn.setRequestProperty(CodeDefine.HTTP_USER_AGENT[0],
                    CodeDefine.HTTP_USER_AGENT[1]);
        }
        if (httpconn != null) {
            httpdis = httpconn.openDataInputStream();
            httpdos = httpconn.openDataOutputStream();
        } else {
            throw new Exception("HttpConnection Cannot be set null");
        }
    }

    private void closeConnection(){
        if (httpdis != null) {
            try {
                httpdis.close();
                httpdis = null;
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        if (httpdos != null) {
            try {
                httpdos.close();
                httpdos = null;
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        if (httpconn != null) {
            try {
                if(connected)
                    httpconn.close();
                httpconn = null;
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized void setConnected(boolean connected) {
        this.runningOver = true;
        this.connected = connected;
    }

    /**
     * 关闭连接
     */
    public synchronized void notifyStop() {
        this.connected = false;
        this.runningOver = true;
        closeConnection();
    }

    public void run() {
        try {
            tryConnect("http://wap.baidu.com:80", User.getUser().isProxy());
            setConnected(true);
        } catch (Throwable e) {
            if (e instanceof SecurityException) {
                Utilities.debug("您没有同意网络连接!");
            }
            setConnected(false);
        } finally {
            closeConnection();
        }
    }
    
    public synchronized void setOver() {
        runningOver = true;
    }

    public synchronized boolean getConnected() {
        return connected;
    }

    public synchronized boolean getOver() {
        return runningOver;
    }

}
